package com.linxcool.ui;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;

/**
 * 对话框
 * @author: linxcool.hu
 */
public class DialogUi implements Callback {

	Activity activity;
	Dialog dialog;
	Handler handler;
	OnKeyUpListener keyUpListener;

	/**
	 * 设置按键抬起监听
	 * @param keyUpListener
	 */
	public void setOnKeyUpListener(OnKeyUpListener keyUpListener){
		this.keyUpListener = keyUpListener;
	}
	
	public DialogUi(Activity activity) {
		this.activity = activity;
		this.handler = new Handler(this);
	}

	/**
	 * 获取状态栏高度
	 * @param activity
	 * @return
	 */
	static int statusBarHeight(Activity activity) {
		Rect frame = new Rect();
		Window window = activity.getWindow();
		window.getDecorView().getWindowVisibleDisplayFrame(frame);
		return frame.top;
	}

	private void initDialog() {
		dialog = new Dialog(activity) {
			@Override
			public boolean onKeyUp(int keyCode, KeyEvent event) {
				if(keyUpListener!=null)
					return keyUpListener.onKeyUp(keyCode, event);
				return false;
			}
		};
		if (statusBarHeight(activity) == 0) dialog.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		dialog.getWindow().setBackgroundDrawable(new ColorDrawable());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCancelable(false);
		dialog.show();
		dialog.getWindow().setLayout(
				LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
	}

	/**
	 * 设置对话框显示的内容
	 * @param view
	 */
	public void setContentView(View view) {
		if (dialog == null)
			initDialog();
		Message msg = handler.obtainMessage(0);
		msg.obj = view;
		handler.sendMessage(msg);
	}

	/**
	 * 通过ID查找对话框内的视图
	 * @param id
	 * @return
	 */
	public View findViewById(int id) {
		return dialog.findViewById(id);
	}

	/**
	 * 取消对话框
	 */
	public void dismiss() {
		if (null != dialog) {
			dialog.dismiss();
			dialog = null;
		}
	}

	/**
	 * 判断对话框是否处于显示状态
	 * @return
	 */
	public boolean isShowing() {
		if (dialog == null)
			return false;
		return dialog.isShowing();
	}

	@Override
	public boolean handleMessage(Message msg) {
		if (dialog == null)
			return false;
		LayoutParams params = new LayoutParams(
				LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		View v = (View) (msg.obj);
		dialog.setContentView(v, params);
		return false;
	}

}
